package com.zimmur.solr.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.solr.client.solrj.SolrQuery.SortClause;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.StringUtils;
import org.apache.solr.common.util.NamedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.zimmur.solr.SolrUtil;
import com.zimmur.solr.common.Facet;
import com.zimmur.solr.common.SolrData;
import com.zimmur.solr.model.Goods;
import com.zimmur.solr.model.SearchableGoods;
import com.zimmur.solr.service.ISolrGoodsService;
import com.zimmur.tools.PageUtil;



@Service("solrGoodsService")
public class SolrGoodsServiceImpl implements ISolrGoodsService {
	Logger log=LoggerFactory.getLogger(SolrGoodsServiceImpl.class);
	@Resource
	private SolrUtil<Goods> solrUtil;
		
	public List<Goods> query(int type,String title,int typeflag,List<SortClause> value,int pageNo){
		List<Goods> goodsList=null;
		StringBuffer q=new StringBuffer("*:*");
		if(type>0){
			q.append(" AND "+SearchableGoods.TYPEID_FIELD+":"+type);
		}
		if(!StringUtils.isEmpty(title)){
			q.append(" AND "+SearchableGoods.TITLE_FIELD+":"+title);
		}
		if(typeflag>0){
			q.append(" AND "+SearchableGoods.TYPEFLAG_FIELD+":"+typeflag);
		}
		try {
			QueryResponse queryResponse=solrUtil.query(q.toString(), null, value, pageNo, SolrData.CORE_GOODS);
			goodsList=queryResponse.getBeans(Goods.class);
		} catch (SolrServerException e) {
			log.error(e.getMessage(),e);
		} catch (IOException e) {
			log.error(e.getMessage(),e);
		}
		return goodsList;
	}
	public List<Goods> queryAll(int type,String title,int typeflag){
		List<Goods> goodsList=null;
		StringBuffer q=new StringBuffer("*:*");
		if(type>0){
			q.append(" AND "+SearchableGoods.TYPEID_FIELD+":"+type);
		}
		if(!StringUtils.isEmpty(title)){
			q.append(" AND "+SearchableGoods.TITLE_FIELD+":"+title);
		}
		if(typeflag>0){
			q.append(" AND "+SearchableGoods.TYPEFLAG_FIELD+":"+typeflag);
		}
		try {
			QueryResponse queryResponse=solrUtil.queryAll(q.toString(),SolrData.CORE_GOODS);
			goodsList=queryResponse.getBeans(Goods.class);
		} catch (SolrServerException e) {
			log.error(e.getMessage(),e);
		} catch (IOException e) {
			log.error(e.getMessage(),e);
		}
		return goodsList;
	}
	public Map<String ,Object> queryWithfacet(int typeId,String keyword,int typeflag,List<SortClause> value,int pageNo,Facet facet){
		Map<String ,Object> map=new HashMap<>();
		//StringBuffer q=new StringBuffer("*:*");
		String q=SearchableGoods.TYPEFLAG_FIELD+":"+typeflag;
		String fq[]=null;
		List<String> fqList=new ArrayList<>();
		if(typeId>0){
			fqList.add(SearchableGoods.TYPEID_FIELD+":"+typeId);
		}
		if(!StringUtils.isEmpty(keyword)){
			fqList.add(SearchableGoods.TITLE_FIELD+":*"+keyword+"*");
		}
		if(fqList.size()>0){
			fq=fqList.toArray(new String[fqList.size()]);
		}
		try {
			QueryResponse queryResponse=solrUtil.queryWithFacet(q, fq, value, pageNo, facet, SolrData.CORE_GOODS);
			map.put("goodsList", queryResponse.getBeans(Goods.class));
			map.put("FacteList", queryResponse.getFacetFields());
		} catch (SolrServerException e) {
			log.error(e.getMessage(),e);
		} catch (IOException e) {
			log.error(e.getMessage(),e);
		}
		return map;
	}
	public int deleteById(String goodsId){
		int flag=1;
		UpdateResponse updateResponse;
		try {
			updateResponse = solrUtil.deleteById(goodsId, SolrData.CORE_GOODS);
			flag=updateResponse.getStatus();
			solrUtil.commit(SolrData.CORE_GOODS);
		} catch (SolrServerException e) {
			log.error(e.getMessage(),e);
			solrUtil.rollback(SolrData.CORE_GOODS);
			flag=-1;
		} catch (IOException e) {
			log.error(e.getMessage(),e);
			solrUtil.rollback(SolrData.CORE_GOODS);
			flag=-1;
		}
		return flag;
	}
	public int add(Goods goods){
		int flag=1;
		UpdateResponse updateResponse;
		try {
			updateResponse = solrUtil.add(goods, SolrData.CORE_GOODS);
			flag=updateResponse.getStatus();
			solrUtil.commit(SolrData.CORE_GOODS);
		} catch (SolrServerException e) {
			log.error(e.getMessage(),e);
			solrUtil.rollback(SolrData.CORE_GOODS);
			flag=-1;
		} catch (IOException e) {
			log.error(e.getMessage(),e);
			solrUtil.rollback(SolrData.CORE_GOODS);
			flag=-1;
		}
		return flag;
	}
//	@Override
//	public PageUtil<Goods> queryGoods(List<Integer> typeIds,String keyword, int typeflag, 
//			List<SortClause> orderByClause, int pageNo) {
//		
//		PageUtil<Goods> page=new PageUtil<>();
//		List<Goods> goodsList=null;
//		String q=SearchableGoods.TYPEFLAG_FIELD+":"+typeflag+" AND　"+ SearchableGoods.DISPLAYSTATUS_FIELD+":"+1;
//		List<String> fqList=new ArrayList<>();
//		
//		if(!StringUtils.isEmpty(keyword)){
//			fqList.add(SearchableGoods.SEARCH_KEYWORD+":"+keyword);
//		}else{
//			String type_sole="";
//			for(Integer typeId:typeIds){
//				type_sole+="OR "+SearchableGoods.TYPEID_FIELD+":"+typeId+" ";
//			}
//			if(type_sole.length()>0){
//				fqList.add(type_sole.substring(2, type_sole.length()));
//			}
//		}
//		String fq[]=null;
//		if(fqList.size()>0)
//			fq=fqList.toArray(new String[fqList.size()]);
//		
//		QueryResponse queryResponse = searchSolrData(q, fq,orderByClause,0, pageNo);
//		if(queryResponse!=null){
//			goodsList=queryResponse.getBeans(Goods.class);
//			int totalFound = (int)queryResponse.getResults().getNumFound();
//			page.setTotalRecord(totalFound);
//			page.setItemList(goodsList);
//		}
//		
//		return page;
//	}
	@Override
	public int addList(List<Goods> goodses) {
		int flag=1;
		UpdateResponse updateResponse;
		try {
			updateResponse = solrUtil.addList(goodses, SolrData.CORE_GOODS);
			flag=updateResponse.getStatus();
			solrUtil.commit(SolrData.CORE_GOODS);
		} catch (SolrServerException e) {
			log.error(e.getMessage(),e);
			solrUtil.rollback(SolrData.CORE_GOODS);
			flag=-1;
		} catch (IOException e) {
			log.error(e.getMessage(),e);
			solrUtil.rollback(SolrData.CORE_GOODS);
			flag=-1;
		}
		return flag;
	}
	@Override
	public PageUtil<Goods> queryGoods(List<String> typeIds,String keyword,String tags, int typeflag, List<SortClause> orderByClause, 
			String offPercent,String goodSizeCode,String goodColorName,String price,int pageSize,int pageNo) {
		PageUtil<Goods> page=new PageUtil<>();
		if(pageSize>0){
			page.setPageSize(pageSize);
		}
		List<Goods> goodsList=null;
		String q=SearchableGoods.TYPEFLAG_FIELD+":"+typeflag+" AND　"+ SearchableGoods.DISPLAYSTATUS_FIELD+":"+1;
		q = decorateParameter(q,offPercent, goodSizeCode,goodColorName,price);
		List<String> fqList=new ArrayList<>();
		String type_sole="";
		if(!StringUtils.isEmpty(tags)){
			String[] splitTags = tags.split(",");
			for (String tag : splitTags) {
				type_sole+="OR "+SearchableGoods.TAGS_FIELD+":*"+tag+"* ";
			}
			if(type_sole.length()>0){
				fqList.add(type_sole.substring(2, type_sole.length()));
			}
			type_sole="";
		}
		if(typeIds.size()>0){
			for(String typeId:typeIds){
				type_sole+="OR "+SearchableGoods.TYPEID_FIELD+":"+typeId+" ";
			}
			if(type_sole.length()>0){
				fqList.add(type_sole.substring(2, type_sole.length()));
			}
			type_sole="";
		}
		if(!StringUtils.isEmpty(keyword)){
			fqList.add(SearchableGoods.SEARCH_KEYWORD+":"+keyword);
		}
		
		String fq[]=null;
		if(fqList.size()>0)
			fq=fqList.toArray(new String[fqList.size()]);
		
		Facet facet = new Facet();
		facet.setStatus(true);
		facet.setFields(new String[]{SearchableGoods.MAINCOLOR_FIELD});
		facet.setLimit(20);
		QueryResponse queryResponse = searchSolrData(q, fq,orderByClause,pageSize, pageNo,facet);
		if (queryResponse != null) {
			goodsList = queryResponse.getBeans(Goods.class);
			int totalFound = (int) queryResponse.getResults().getNumFound();
			page.setPageNo(pageNo);
			page.setTotalRecord(totalFound);
			page.setItemList(goodsList);
			List<FacetField> facetFields = queryResponse.getFacetFields();
			if (facetFields != null && !facetFields.isEmpty()){
				page.insertFacetAll(facetFields);
			}
		}
		return page;
	}
	
	private QueryResponse searchSolrData(String q, String[] fq, List<SortClause> orderByClause, int pageSize,
			int pageNo,Facet facet) {
		try {
			QueryResponse queryResponse = solrUtil.query(q, fq, orderByClause, pageSize, pageNo, 
					facet,SolrData.CORE_GOODS);
			return queryResponse;
		} catch (SolrServerException e) {
			log.error(e.getMessage(), e);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}
	/**
	* @Title: decorateParameter 
	* @Description: 包装商品筛选条件
	* @param  q 初始查询条件
	* @param  typeId 商品分类，值为null或0不做为筛选条件
	* @param  offPercent 折扣，格式：30(单个数据)，30-50(区间数据)
	* @param  goodSizeCode 商品尺码，格式：L
	* @param  price  商品价格：格式：30(单个数据)，30-50(区间数据)
	
	* @return String    返回类型 
	
	* @throws
	 */
	private String decorateParameter(String q,String offPercent,
			String goodSizeCode,String goodColorName,String price) {
		if(!StringUtils.isEmpty(offPercent)){
			if(offPercent.indexOf("-")>=0){
				String[] splitOffPercent = offPercent.split("-");
				if(splitOffPercent.length == 2){
					q+=" AND "+SearchableGoods.OFFPERCENT_FIELD+":["+splitOffPercent[0]+" TO "+splitOffPercent[1]+"]";
				}
			}else{
				q+=" AND "+SearchableGoods.OFFPERCENT_FIELD+":["+offPercent+" TO *]";
			}
		}
		if(!StringUtils.isEmpty(goodSizeCode)){
			q+=" AND "+SearchableGoods.GOODSIZECODE_FIELD+":*"+goodSizeCode+"*";
		}
		if(!StringUtils.isEmpty(goodColorName)){
			q+=" AND "+SearchableGoods.MAINCOLOR_FIELD+":"+goodColorName;
		}
		if(!StringUtils.isEmpty(price)){
			if(price.indexOf("-")>=0){
				String[] splitPrice = price.split("-");
				if(splitPrice.length == 2){
					q+=" AND "+SearchableGoods.PRICE_FIELD+":["+splitPrice[0]+" TO "+splitPrice[1]+"]";
				}
			}else{
				q+=" AND "+SearchableGoods.PRICE_FIELD+":["+price+" TO *]";
			}
		}
		return q;
	}
	@Override
	public List<Goods> queryRecommendIndexGoods(int rowsSize,List<SortClause> orderByClause) {
		List<Goods> goodsList=null;
		StringBuffer q=new StringBuffer();
		q.append(SearchableGoods.DISPLAYSTATUS_FIELD+":"+1);
		q.append(" AND "+SearchableGoods.RECOMMANDTYPE_FIELD+":3");
		try {
			QueryResponse queryResponse=solrUtil.queryByRowsSize(q.toString(), orderByClause, rowsSize, SolrData.CORE_GOODS);
			goodsList=queryResponse.getBeans(Goods.class);
		} catch (SolrServerException e) {
			log.error(e.getMessage(),e);
		} catch (IOException e) {
			log.error(e.getMessage(),e);
		}
		return goodsList;
	}
	@Override
	public List<Goods> queryGoodsById(List<String> goodsIds) {
		List<Goods> goodsList=null;
		String q = SearchableGoods.DISPLAYSTATUS_FIELD+":"+1;
		List<String> fqList=new ArrayList<>();
		String fqString="";
		if(!goodsIds.isEmpty()){
			for(String goodsId:goodsIds){
				fqString+="OR "+SearchableGoods.ID_FIELD+":"+goodsId+" ";
			}
			if(fqString.length()>0){
				fqList.add(fqString.substring(2, fqString.length()));
			}
			fqString=null;
		}
		String fq[]=null;
		if(fqList.size()>0)
			fq= fqList.toArray(new String[fqList.size()]);
		try {
			QueryResponse queryResponse = solrUtil.queryAll(q, fq,SolrData.CORE_GOODS);
			if(queryResponse!=null){
				goodsList=queryResponse.getBeans(Goods.class);
			}
		} catch (SolrServerException e) {
			log.error(e.getMessage());
		} catch (IOException e) {
			log.error(e.getMessage());
		}
		
		return goodsList;
	}
}
